import { defineStore } from 'pinia'
import axios from 'axios'

export const useAuthStore = defineStore('auth', {
  state: () => {
    // 安全地解析 localStorage 中的 user 数据
    let user = null
    try {
      const userStr = localStorage.getItem('user')
      if (userStr) {
        user = JSON.parse(userStr)
      }
    } catch (error) {
      console.error('Failed to parse user data from localStorage', error)
      // 清除损坏的数据
      localStorage.removeItem('user')
    }
    
    return {
      token: localStorage.getItem('token') || null,
      user: user,
      isAdmin: localStorage.getItem('isAdmin') === 'true' || false,
      loading: false,
      error: null
    }
  },
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    userRole: (state) => state.isAdmin ? 'admin' : 'user'
  },
  
  actions: {
    async login(credentials) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.post('/api/user/login', {
          loginName: credentials.loginName,
          password: credentials.password
        })
        
        if (response.data.success) {
          if (!response.data.token && response.data.user) {
            response.data.token = `user_${Date.now()}`
          }
          
          this.setUserData(response.data, false)
        }
        
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '登录失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async adminLogin(credentials) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.post('/api/admin/login', {
          loginName: credentials.loginName,
          password: credentials.password
        })
        
        if (response.data.success) {
          if (!response.data.token && response.data.admin) {
            response.data.token = `admin_${Date.now()}`
            response.data.user = response.data.admin
          }
          
          this.setUserData(response.data, true)
        }
        
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '管理员登录失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async register(userData) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.post('/api/user/register', userData)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '注册失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async fetchUserProfile() {
      if (!this.token) return null
      
      this.loading = true
      try {
        const endpoint = this.isAdmin ? '/api/admin/profile' : '/api/user/profile'
        
        // 添加 userId 参数
        const userId = this.user?.userId || localStorage.getItem('userId')
        
        if (!userId && !this.isAdmin) {
          console.error('No userId available for profile fetch')
          return null
        }
        
        const params = this.isAdmin ? {} : { userId }
        
        console.log('Fetching user profile with params:', params)
        
        const response = await axios.get(endpoint, {
          headers: { Authorization: `Bearer ${this.token}` },
          params
        })
        
        console.log('User profile response:', response.data)
        
        if (response.data.success && response.data.user) {
          this.user = response.data.user
          
          // 确保性别字段有默认值
          if (!this.user.gender) {
            this.user.gender = '保密'
          }
          
          // 安全地保存用户数据
          try {
            localStorage.setItem('user', JSON.stringify(this.user))
          } catch (error) {
            console.error('Failed to save user data to localStorage', error)
          }
        }
        
        return response.data
      } catch (error) {
        console.error('Error fetching user profile:', error)
        if (error.response?.status === 401) {
          this.logout()
        }
        throw error
      } finally {
        this.loading = false
      }
    },
    
    setUserData(data, isAdmin = false) {
      const token = data.token || `${isAdmin ? 'admin' : 'user'}_${Date.now()}`
      const user = data.user || data.admin || {}
      
      this.token = token
      this.user = user
      this.isAdmin = isAdmin
      
      localStorage.setItem('token', token)
      
      // 安全地保存用户数据
      try {
        localStorage.setItem('user', JSON.stringify(user))
        // 新增：单独存储 userId（数据库主键）
        if (user && user.userId) {
          localStorage.setItem('userId', user.userId)
        } else if (user && user.id) {
          localStorage.setItem('userId', user.id)
        }
      } catch (error) {
        console.error('Failed to save user data to localStorage', error)
      }
      
      localStorage.setItem('isAdmin', isAdmin.toString())
      
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
    },
    
    logout() {
      this.token = null
      this.user = null
      this.isAdmin = false
      
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('isAdmin')
      
      delete axios.defaults.headers.common['Authorization']
    },
    
    async updateProfile(userData) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.put('/api/user/update', userData)
        
        if (response.data.success) {
          // 更新本地用户数据
          this.user = { ...this.user, ...userData }
          // 更新 localStorage 中的用户数据
          localStorage.setItem('user', JSON.stringify(this.user))
        }
        
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '更新个人资料失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async changePassword(passwordData) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.put('/api/user/change-password', passwordData)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '修改密码失败'
        throw error
      } finally {
        this.loading = false
      }
    }
  }
}) 